﻿#region

using Microsoft.AspNetCore.Http;
using Vin.Extension.Framework.Dto;
using Vin.Extension.Framework.Login.Entities;
using Vin.Extension.Framework.Login.Options;
using Vin.Extension.Framework.Login.ServiceInterface;
using Vin.Extension.Framework.Models;
using Vin.Extension.Framework.Monitor.ServiceInterface;
using Vin.Extension.JwtBearer.Tool;
using Vin.Tool.AspNetCore.Service;
using Vin.Tool.AspNetCore.Singleton;
using Vin.Tool.Attributes;

#endregion

namespace Vin.Extension.Framework.Login.Service;

public class SysLoginService : VinBaseService, ISysLoginService
{
    [Inject] private readonly ISysLoginLogService _sysLoginLogService = null!;

    /// <summary>
    /// 登出
    /// </summary>
    public async Task LogoutAsync()
    {
        VinSecurityTool.LogoutAuthorizeToken();
        await Task.CompletedTask;
    }

    public async Task AddLoginLogAsync(long? accountId, string? account, bool isSuccess, string? msg, string? loginType,
        object? loginInfo)
    {
        await _sysLoginLogService.AddLoginLogAsync("system", accountId, account, isSuccess, msg, loginType, loginInfo,
            null, null);
    }

    public async Task UpdateLoginSuccessLogAsync(long? employeeId = null, string? employeeName = null)
    {
        await _sysLoginLogService.UpdateLoginLogAsync(employeeId, employeeName);
    }

    public async Task<string> CreateTokenAsync(SysAccount account, string? loginType,
        object? loginInfo)
    {
        // 记录登录成功日志
        await AddLoginLogAsync(account.Id, account.Account, true, "登录成功", loginType, loginInfo);

        var adminOption = VinApp.GetConfig<AdminOption>();
        adminOption.SuperAdmins ??= new List<string>() { "vin" };

        return await Task.FromResult(VinSecurityTool.CreateAuthorizeToken(new VinTokenModel()
        {
            RealAccountId = account.Id,
            AccountName = account.Account,
            IsSuperAdmin = adminOption.SuperAdmins.Contains(account.Account!), //account.Account == "vin",
            TerminalType = "PC",
        }, null, 1));
    }

    // --------------------- 以下为私有代码 ---------------------
}